
var data1 = [{'id':'1','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'完成箱'},{'id':'2','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'垃圾箱'},
    {'id':'3','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'待批箱'},{'id':'4','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'草稿箱'},
    {'id':'5','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'已批箱'},{'id':'6','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'草稿箱'}];

var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate, cuName = getQueryVariable("customerName");
var opers="",salemans="";//所属业务员，所属操作员
lay('.starttime').each(function(){
    laydate.render({
        elem: this,
        max: 0,//最大值为当前日期
        eventElem: '#starttime',//日期输入框的图标，给图标也绑定点击事件
        trigger: 'click'
        //,value: new Date() //默认值30天前
    });
});


//判断当前登录用户是否为 营销部门的总监 管理员角色 true:是 false 否
let isMarketingDirectorMsn="是";
is_marketing_director_msn();
let isMsn="是";
is_msn();
//是否有 工厂统计及费用方式 权限，如果有标签赋值true 并设置不显示
let factoryStatisticsCost=false;
factory_statistics_cost();
if (factoryStatisticsCost){
    document.getElementById("statisticsDiv").style.display = "none";
}
//统计
layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("shipmentPlanStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/tpl/shipmentPlanStatistics1.jsp","出运结汇一览总表")
                break
        }
    });
})


var documenttype=JSON.parse(window.sessionStorage.getItem("documenttype"));//单据信息
var documentsinformation = JSON.parse(window.sessionStorage.getItem("documentsinformation"));   //单据信息
var subordinatesalesman=JSON.parse(window.sessionStorage.getItem("subordinatesalesman"));//所属业务员
var  owneroperator=JSON.parse(window.sessionStorage.getItem("owneroperator"));//所属操作员
var startsdate = JSON.parse(window.sessionStorage.getItem("startsdate")); //签约开始日期
var endsdate=JSON.parse(window.sessionStorage.getItem("endsdate"));//签约结束日期
var  signingcompany=JSON.parse(window.sessionStorage.getItem("signingcompany"));//签约公司
var startshdate=JSON.parse(window.sessionStorage.getItem("startshdate"));//出运开始日期
var endshdate = JSON.parse(window.sessionStorage.getItem("endshdate"));//出运结束日期
var djtype=getdictionary(6,49);//单据类型，从字典中取

var fpzje=getAllRolesByCurr("shipmentplan_newupshipmentplan");//判断是否有此角色
getLoginUserInfo();
setselecttype(djtype,"documenttype");
let getSTreeElem;//业务员下拉框对象
let getOTreeElem;//操作员下拉框对象
let deptOperationList=[];
let deptSalesmanList=[];

initTree();
form.render();//表单刷新

let whereData={};
if (cuName!=null && cuName!=''){
    let cName = decodeURI(cuName);
    $("#customerName").val(cName);

    let salesmanCode = getSTreeElem.getValue('value').join();
    let executor = getOTreeElem.getValue('value').join();

    let deptSalesmanCode = deptSalesmanList.getValue('value').join();
    let deptExecutor = deptOperationList.getValue('value').join();

    whereData.salesman= salesmanCode
    whereData.executor= executor
    whereData.deptSalesmanCode= deptSalesmanCode
    whereData.deptOperationCode= deptExecutor

    whereData.customerName= cName
}else {
    whereData.salesman= user.code
    whereData.executor= user.code
}
table.render({
    elem: '#shipmentplanselect'
   // ,data:data1
    ,toolbar: '#shipmentplantoolbar'
    ,url:"shipmentPlan/selectShipmentPlanListByPage"
    ,where: whereData
    ,method:"get"
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'id',hide: true,width: 120}
        ,{field:'shipmentNo', title:'计划编号',sort:true,width: 120,event: "projectnumber"}
        ,{field:'customerName', title:'客户名称',sort:true,width: 120}
        ,{field:'shipmentDate', title:'出运日期',sort:true,width: 120}
        ,{field:'currency', title:'币种',sort:true,width: 120}
        ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
        ,{field:'startPlace', title:'起运地',sort:true,width: 120}
        ,{field:'endPlace', title:'目的地',sort:true,width: 120}
        ,{field:'paymentTerm', title:'收款类型',sort:true,width: 120}
        ,{field:'priceTerm', title:'价格术语',sort:true,width: 120}
        ,{field:'invoiceAmount', title:'发票总额',sort:true,width: 120 , totalRow: true}
        ,{field:'makeTime', title:'制单日期',sort:true,width: 120}
        ,{field:'salesContractNo', title:'销售合同号',sort:true,width: 120}
        ,{field:'customerContractNo', title:'客户合同号',sort:true,width: 120}
        ,{field:'salesmanCode', title:'业务员',sort:true,width: 120}
        ,{field:'businessMode', title:'业务模式',sort:true,width: 120}
        ,{field:'proFinishDate', title:'货号日期',sort:true,width: 120}
        ,{field:'brand', title:'品牌',sort:true,width: 120}
        ,{field:'stock', title:'仓库',sort:true,width: 120}
        ,{field:'containerType', title:'货柜型号',sort:true,width: 120}
        // ,{field:'boxType', title:'箱型',sort:true,width: 120}
        ,{field:'payDay', title:'账期',sort:true,width: 120}
        ,{field:'declareCompany', title:'报关抬头',sort:true,width: 120}
        ,{field:'companyCode', title:'签约公司',sort:true,width: 120}
        ,{field:'executorCode', title:'操作员',sort:true,width: 120}
        ,{field:'boxStatus', title:'单据类型',sort:true,width: 120}
        ,{field:'customerLevelName', title:'客户等级名称',sort:true,width: 120}
        ,{field:'customerLevelCode', title:'客户等级编码',sort:true,width: 120}
        ,{fixed: 'right', width:240, toolbar: '#shipmentplaneditor', title:'操作'}
    ]]
    ,id: 'shipmentplantableid'
    ,height: $(document).height() - $('#shipmentplanselect').offset().top - 50
    ,page: true
    ,done:function (res, curr, count) {
        if(fpzje){
            $("[data-field='invoiceAmount']").css("display", "none");
        }


        var company = getCompany();   //签约公司

        getselectText(company,"companyCode");
        var boxStatus=getBosstatus();
        getselectText(boxStatus,"boxStatus");

    }
    ,limit:50   //默认十条数据一页
    ,limits:[50,100,200,300,500,1000]  //数据分页条
});
function getBosstatus() {
    var obj=[];
    var data1={};
    var data2={};
    var data3={};
    var data4={};
    var data5={};
    data1.code='1';
    data2.code='2';
    data3.code='3';
    data4.code='4';
    data5.code='5';
    data1.name="草稿";
    data2.name="待批";
    data3.name="已批";
    data4.name="完成";
    data5.name="垃圾";
    obj.push(data1);
    obj.push(data2);
    obj.push(data3);
    obj.push(data4);
    obj.push(data5);
    return obj;
    /*

    data.code=da.data[i].code;
    data.name=da.data[i].name;*/

    /* 审核状态1：草稿 2：待批  3：已批  4：完成  5：垃圾*/
}
setPullMenu();
//修改、删除
table.on('tool(shipmentplantable)', function(obj){
    var data = obj.data;
    //修改出运计划
    if(obj.event === 'update') {
        parent.intab("views/jsp/ExportBusiness/tpl/newupshipmentplan.jsp?id="+obj.data.id,"修改出运计划")
    }else if(obj.event === 'delect'){
        layer.confirm('真的删除行么', function (index) {
            if(data.boxStatus == '1'){//放入垃圾箱
                if(updateStatus(data.id,5)){
                    layer.msg('删除成功');
                    refrash(obj.data);
                }else{
                    layer.msg('删除失败');
                }
            }else{
                if(data.id !=null){
                    if(del(data.id)){//物理删除
                        layer.msg('删除成功');
                        refrash(obj.data);
                    }else{
                        layer.msg('删除失败');
                    }
                }
            }

        });

    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            if(updateStatus(data.id,2)){
                layer.msg('提交审批成功');
                refrash(obj.data);
            }else{
                layer.msg('提交审批失败');
            }

        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            var num=updateStatus2(data.id,3);
            if(num ==1){
                layer.msg('审批通过');
                refrash(obj.data);
            }else if(num == -1){
                layer.msg('出运计划已被出运明细引用');
            }else {
                layer.msg('审批失败');
            }

        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            var num=updateStatus2(data.id,1);
            if(num == 1){
                layer.msg('审批退回通过');
                refrash(obj.data);
            }else if(num == -1){
                layer.msg('出运计划已被出运明细,不能进行退回');
            }
            else{
                layer.msg('审批退回失败');
            }

        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            if(updateStatus(data.id,4)){
                layer.msg('完成通过');
                refrash(obj.data);
            }else{
                layer.msg('完成失败');
            }

        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            if(updateStatus(data.id,1)){
                layer.msg('还原通过');
                refrash(obj.data);
            }else{
                layer.msg('还原失败');
            }

        });
    }else if(obj.event === 'back'){
        layer.confirm('确定退回吗', function (index) {
            if(updateStatus(data.id,3)){
                layer.msg('退回通过');
                refrash(obj.data);
            }else{
                layer.msg('退回失败');
            }

        });
    }else if (obj.event === "projectnumber"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewshipmentplan.jsp?id="+data.id,"出运计划明细")
    }
});
//刷新出运计划列表
function refrash(data) {
   let salesman=$("input[name='subordinatesalesman']")[0].value;//所属业务员
   let executor=    $("input[name='owneroperator']")[0].value;//所属操作员
    if(salesman==""){
        salesman=user.code;
    }
    if(executor==""){
        executor=user.code;
    }
    table.reload('shipmentplantableid', {
        method:"get",
        url: "shipmentPlan/selectShipmentPlanListByPage",
        where: {
            "boxStatus": $("select[name='documenttype']")[0].value,//单据类型
            "numberLike":  $("input[name='documentsinformation']")[0].value,//出运计划编号
            "salesman": salesman,//$("input[name='subordinatesalesman']")[0].value,//所属业务员
            "executor": executor,//$("input[name='owneroperator']")[0].value,//所属操作员
            "signingcompany": $("select[name='signingcompany']")[0].value,//签约公司
            "startMakeTime": $("input[name='startMakeTime']")[0].value,//制单日期
            "endMakeTime": $("input[name='endMakeTime']")[0].value,//制单日期
            "startShipmentTime": $("input[name='startshdate']")[0].value,//出运日期
            "endShipmentTime": $("input[name='endshdate']")[0].value//

        } //查询条件
        // where: JSON.stringify(data.field)
        ,page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');
    return false;
}
//搜索
form.on('submit(submitform)', function(data){
    let operation = data.field.owneroperator;
    let salesman = data.field.subordinatesalesman;
    let productCode = data.field.productCode;
    let customerName = data.field.customerName;

    let deptSalesmanCode = data.field.deptSalesmanCode;
    let deptExecutor = data.field.deptOperationCode;



   /* if(isEmpty(operation) && isEmpty(salesman)){
        return;
    }*/
    if(operation =="" && salesman=="" && deptSalesmanCode=="" && deptExecutor==""){
        operation=user.code;
        salesman=user.code;
    }
    table.reload('shipmentplantableid', {
        method:"get",
        url: "shipmentPlan/selectShipmentPlanListByPage",
         where: {
             "boxStatus": $("select[name='documenttype']")[0].value,//单据类型
             "numberLike":  $("input[name='documentsinformation']")[0].value,//出运计划编号
             "salesman": salesman,//data.field.subordinatesalesman,//所属业务员
             "executor": operation,//data.field.owneroperator,//所属操作员
             "deptSalesmanCode":deptSalesmanCode,
             "deptOperationCode":deptExecutor,
             "signingcompany": $("select[name='signingcompany']")[0].value,//签约公司
             "startMakeTime": $("input[name='startMakeTime']")[0].value,//制单日期
             "endMakeTime": $("input[name='endMakeTime']")[0].value,//
             "startShipmentTime": $("input[name='startshdate']")[0].value,//出运日期
             "endShipmentTime": $("input[name='endshdate']")[0].value,//
             "salesContractNo": $("input[name='salesContractNo']")[0].value,//销售合同号
             "productCode":productCode,
             "customerName":customerName,

         } //查询条件
        // where: JSON.stringify(data.field)
        ,page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');
    return false;
});

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
//新增出运计划
table.on('toolbar(shipmentplantable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newupshipmentplan.jsp","新增出运计划");
            break;
        case 'prints':
            if(checkStatus.data.length > 1){
                layer.msg("每次只能打印一个出运计划!");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的出运计划!");
                break;
            }
            window.open("views/jsp/report.jsp?ym=shipment&code=code:"+checkStatus.data[0].shipmentNo)


            break;
    };
});
layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {
        var checkStatus = table.checkStatus("shipmentplantableid");
        if(checkStatus.data.length > 1){
            layer.msg( "每次只能打印一个出运计划! ");
            return false;
        }
        if(checkStatus.data.length == 0){
            layer.msg("请选择要打印的出运计划! ");
            return false;
        }
        switch (event) {
            case "shipment":
                window.open("views/jsp/report.jsp?ym=shipment&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "warehousePickUpShipmentPlanReport":
                window.open("views/jsp/report.jsp?ym=warehousePickUpShipmentPlanReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "salesShipment":
                window.open("views/jsp/report.jsp?ym=salesShipmentReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanPackingFormatReport_RTCO_PL":
                window.open("views/jsp/report.jsp?ym=shipmentPlanPackingFormatReport_RTCO_PL&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanInvoiceFormatReport_RTCO_CI":
                window.open("views/jsp/report.jsp?ym=shipmentPlanInvoiceFormatReport_RTCO_CI&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanPackingFormatReport_GENSYU_PL_HK":
                window.open("views/jsp/report.jsp?ym=shipmentPlanPackingFormatReport_GENSYU_PL_HK&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanInvoiceFormatReport_GENSYU_CI_HK":
                window.open("views/jsp/report.jsp?ym=shipmentPlanInvoiceFormatReport_GENSYU_CI_HK&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanPackingFormatReport_GENSYU_PL_SHANGHAI":
                window.open("views/jsp/report.jsp?ym=shipmentPlanPackingFormatReport_GENSYU_PL_SHANGHAI&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanInvoiceFormatReport_GENSYU_CI_SHANGHAI":
                window.open("views/jsp/report.jsp?ym=shipmentPlanInvoiceFormatReport_GENSYU_CI_SHANGHAI&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanPackingFormatReport":
                window.open("views/jsp/report.jsp?ym=shipmentPlanPackingFormatReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanInvoiceFormatReport":
                window.open("views/jsp/report.jsp?ym=shipmentPlanInvoiceFormatReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanContractFormatReport":
                window.open("views/jsp/report.jsp?ym=shipmentPlanContractFormatReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanPackingFormatReportCL":
                window.open("views/jsp/report.jsp?ym=shipmentPlanPackingFormatReportCL&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanInvoiceFormatReportCL":
                window.open("views/jsp/report.jsp?ym=shipmentPlanInvoiceFormatReportCL&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanDeliveryListReport":
                window.open("views/jsp/report.jsp?ym=shipmentPlanDeliveryListReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanBoxStickReport":
                window.open("views/jsp/report.jsp?ym=shipmentPlanBoxStickReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentPlanDeliveryNoteReport":
                window.open("views/jsp/report.jsp?ym=shipmentPlanDeliveryNoteReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
            case "shipmentYFPlanDeliveryNoteReport":
                window.open("views/jsp/report.jsp?ym=shipmentYFPlanDeliveryNoteReport&code=code:"+checkStatus.data[0].shipmentNo)
                break
        }
    });
})
//根据登陆用户部门编码判断显示那个
function getLoginUserInfo() {
    let user;
    //获取当前登陆用户名称
    $.ajax({
        url:"productmaininfo/getLoginUserInfo",
        async:false,
        success:function(data){
            if(data.status == 200){
                user=data.data;
            }
        }
    });
    let currentBtn1 = document.getElementById("printOne");
    let currentBtn2 = document.getElementById("printTwo");
    if (user.departmentCode === "WLCCB01" ) {
        currentBtn2.style.display = "block"; //style中的display属性
    }else{
        currentBtn1.style.display = "block";
    }
}

$("#statistical").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/statistics.jsp","出运计划统计")
});




//获取签约公司
function getCompany() {
    var obj=[];
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'shipmentPlan/getCompany',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){

                for(var i=0;i<da.data.length;i++){
                    var data={};
                    data.code=da.data[i].code;
                    data.name=da.data[i].name;
                    obj.push(data);
                }
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}


//获取用户
function getUser() {
    var obj=[];
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'shipmentPlan/getAllUser',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                for(var i=0;i<da.data.length;i++){
                    var data={};
                    data.code=da.data[i].code;
                    data.name=da.data[i].name;
                    obj.push(data);
                }
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}
//签约公司、所属业务员、所属操作员下拉框 赋值
function setPullMenu(){
    var company = getCompany();   //签约公司
    var user = getUser();   //获取用户

     //当前登录人所管理的员工
  //  var shipmentplanmagage=getManageRule("shipmentplanmagage");////所属操作员
    //var shipmentplansalesman=getManageRule("shipmentplansalesman");//所属业务员


    var signingcompany = $("select[name='signingcompany']"); //签约公司
    //var owneroperator =$("select[name='owneroperator']"); //所属操作员
    //var subordinatesalesman = $("select[name='subordinatesalesman']"); //所属业务员

    signingcompany.append(getoption(company));

    form.render();

}
function  getoption(objs) {
    var stoptions="<option value=''>请选择</option>";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
    return stoptions;
}

function updateStatus2(id,statuss) {
    var num=0;
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        data:{"id":id,"statuss":statuss},
        url:'shipmentPlan/updateByKey2',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                num=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return num;
}

function updateStatus(id,statuss) {
    var tf=false;
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        data:{"id":id,"statuss":statuss},
        url:'shipmentPlan/updateByKey',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

function del(id) {
    var tf=false;
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        data:{"id":id},
        url:'shipmentPlan/delete',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//下拉框赋值
function setselecttype(dt,key) {
    var options="<option value=''>请选择</option>";
    for(var i=0;i<dt.length;i++){
        options+="<option value='"+dt[i].code+"'>"+dt[i].name+"</option>";
    }
    $("#"+key+"").append(options);

}
//获取下拉列表值
function getlxandlevel() {
    var curry=getdictionary(5,14);//币种
    var termspay=getdictionary(5,15);//付款方式
    var priceterm=getdictionary(5,16);//价格术语
    var business=getdictionary(6,20);//业务模式
    var destin = getdictionary(6,29) //目的地
    var places = getdictionary(6,31); //起运地
    var bankValue = getdictionary(6,32); //银行
    var unit = getdictionary(6,42); //单位
    var costtype = getdictionary(5,19);  //费用类型
    var declarecompany=getdictionary(6,48);//报关抬头
    var transmode=getdictionary(2,5);//运输方式
    var stock=getdictionary(4,11);//仓库

    var currency=$("select[name='currency']");//币种
    var priceterms = $("select[name='priceTerm']"); //价格术语
    var termspayment = $("select[name='paymentTerm']"); //收款类型
    var businessmode = $("select[name='businessMode']"); //业务模式
    var place = $("select[name='startPlace']"); //起运地
    var destination = $("select[name='endPlace']"); //目的地
    var bank = $("select[name='bankCode']"); //银行
    var declarecompanystr=$("select[name='declareCompany']");//报关抬头
    var transmodestr=$("select[name='transMode']");//运输方式
    var targetcountrystr=$("select[name='targetCountry']");//运抵国家
    var stockstr=$("select[name='stock']");//仓库
    var unitselect = $("select[name='unitselect']"); //单位
    var costtypeselect = $("select[name='costtypeselect']");   //费用类型


    currency.append(getoption(curry)); //币种
    priceterms.append(getoption(priceterm)); //价格术语
    termspayment.append(getoption(termspay)); //付款方式
    businessmode.append(getoption(business)); //业务模式
    place.append(getoption(places)); //起运地
    destination.append(getoption(destin)); //目的地
    bank.append(getoption(bankValue)); //银行
    unitselect.append(getoption(unit)); //单位
    costtypeselect.append(getoption(costtype));    //费用类型
    declarecompanystr.append(getoption(declarecompany));//报关抬头
    transmodestr.append(getoption(transmode));//运输方式
    targetcountrystr.append(getoption(destin));//运抵国家
    stockstr.append(getoption(stock));//运抵国家

  /*  form.render();*/

}
function getselectText( dt,key){
    $("[data-field = '"+key+"']").children().each(function(){
        for(var i=0;i<dt.length;i++){
            if($(this).text() == dt[i].code){
                $(this).text(dt[i].name);
            }
        }
    })
}
let salesmanCodes="";//所属 业务员下拉框选择值
function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if (cuName!=null && cuName!=''){
            tmparr.selected=true;
        }
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
           /* return this*/
            salesmanCodes="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    salesmanCodes=salesmanCodes+ change[i].value;
                }else{
                    salesmanCodes=salesmanCodes+ change[i].value+",";
                }
            }
        }
    })
}
function initTree() {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    if (treeList && treeList.list) {
        let userTree = getAllJson(treeList.list);
        getOTreeElem = getxmselect("#operationCode", "owneroperator", userTree);
        getSTreeElem = getxmselect("#salesmanCode", "subordinatesalesman", userTree);
    } else {
        getOTreeElem = getxmselect("#operationCode", "owneroperator", [{name: user.name, value: user.code}]);
        getSTreeElem = getxmselect("#salesmanCode", "subordinatesalesman", [{name: user.name, value: user.code}]);
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

}

$("#clear").on("click",function () {
    getOTreeElem.setValue([ ]);
    getSTreeElem.setValue([ ]);
    deptOperationList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
});

//判断当前登录用户是否为 营销部门的总监 管理员 管理角色
function is_marketing_director_msn() {
    $.ajax({
        url:'shipmentPlan/isMarketingDirectorMsn',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                isMarketingDirectorMsn=da.data;
            }
        }
    });
}
//判断当前登录用户是否为 管理员 角色
function is_msn() {
    $.ajax({
        url:'shipmentPlan/isMsn',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                isMsn=da.data;
            }
        }
    });
}

//判断当前登录用户是否有 工厂统计及费用方式 权限
function factory_statistics_cost(){
    $.ajax({
        url:'shipmentPlan/factoryStatisticsCost',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                factoryStatisticsCost=da.data;
            }
        }
    });
}

